Skip to content

feat(metrics): send metrics as OTLP with METRICS_PROTOCOL=otlp - #425

Open
PrashantBtkl wants to merge 1 commit into
mainfrom
feat/nb-41490-otlp-metrics
Open

PrashantBtkl wants to merge 1 commit into
mainfrom
feat/nb-41490-otlp-metrics

Conversation

@PrashantBtkl

Copy link
Copy Markdown
Contributor

What this PR does

Metrics could only be pushed as Prometheus remote write, while traces and logs already use OTLP. METRICS_PROTOCOL=otlp now sends metrics as OTLP/HTTP too. Remote write stays the default.

Metric names, job and instance match remote write. To get that, names carry no unit, counters without a _total suffix go as gauges, and no instrumentation scope or service.version is sent (VictoriaMetrics turns both into labels, which would start new series on every upgrade).

Worth a look

  • VictoriaMetrics adds service.name and service.instance.id labels, so switching an existing host starts new series there.
  • As with remote write, only 400 and 413 drop a payload. The OTLP spec also treats other statuses such as 500 as non-retryable; here they are retried.
  • Encoding costs about 3x the CPU of remote write (20k series: 142 ms vs 50 ms per scrape).
  • Series the agent only reads (kernel, cgroup counters) are sent without a start time.

Linked issue / context

Part of nudgebee/nudgebee-enterprise#41490

How was this tested?

Run with METRICS_PROTOCOL=otlp against http://<prometheus>:9090/api/v1/otlp/v1/metrics (--web.enable-otlp-receiver); up{job="nudgebee-node-agent"} should return the host.

  • go test ./... and go vet ./... pass.
  • Same test registry sent both ways to Prometheus 3.5.0 and VictoriaMetrics 1.122.0 / 1.157.0: identical series apart from the two service.* labels.
  • Real agent on a Linux VM into Prometheus, with the store stopped for part of the run: spooled payloads replayed with no gap. This run was on an earlier revision of the branch; start time and scope handling changed after it.
  • Not tested: an OpenTelemetry Collector as the receiver.

Checklist

  • gofmt, goimports, go vet, go mod tidy
  • tests pass
  • CHANGELOG.md updated under ## [Unreleased]
  • No real credentials, internal hostnames, or production captures in test fixtures

Opt-in; Prometheus remote write stays the default. Metric names and the job and
instance labels match remote write, so existing queries keep working. Reuses the
on-disk spool, with a separate directory per protocol.

Part of nudgebee/nudgebee-enterprise#41490

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request adds support for sending metrics via the OTLP/HTTP protocol as an alternative to Prometheus remote write, introducing a new --metrics-protocol configuration option, OTLP encoding logic, and separate spool directories to prevent payload conflicts. The review feedback suggests optimizing performance by reusing gzip.Writer instances via a sync.Pool during OTLP encoding, and adding a helper function to extract response body summaries for improved error reporting.

Comment thread prom/otlp.go
Comment on lines +3 to +42
import (
"bytes"
"compress/gzip"
"io"
"math"
"sort"
"strings"

dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/model"
collectorpb "go.opentelemetry.io/proto/otlp/collector/metrics/v1"
commonpb "go.opentelemetry.io/proto/otlp/common/v1"
metricspb "go.opentelemetry.io/proto/otlp/metrics/v1"
resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
"k8s.io/klog/v2"
)

// encodeOTLP builds a gzipped OTLP/HTTP request body.
//
// A store must end up with the same series as over remote write, because queries
// select by exact name and by `job` and `instance`. So names are sent as they are
// with no unit (stores derive suffixes from units), and `job` and `instance` are
// set on every data point (not every store derives them from service.*).
func encodeOTLP(mfs []*dto.MetricFamily, timestampMs int64, extraLabels map[string]string) ([]byte, error) {
data, err := proto.Marshal(buildOTLPRequest(mfs, timestampMs, extraLabels))
if err != nil {
return nil, err
}
buf := &bytes.Buffer{}
w := gzip.NewWriter(buf)
if _, err = w.Write(data); err != nil {
return nil, err
}
if err = w.Close(); err != nil {
return nil, err
}
return buf.Bytes(), nil
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To avoid high CPU overhead and excessive memory allocations on every scrape/encode cycle, reuse gzip.Writer instances using a sync.Pool.

import (
	"bytes"
	"compress/gzip"
	"io"
	"math"
	"sort"
	"strings"
	"sync"

	dto "github.com/prometheus/client_model/go"
	"github.com/prometheus/common/model"
	collectorpb "go.opentelemetry.io/proto/otlp/collector/metrics/v1"
	commonpb "go.opentelemetry.io/proto/otlp/common/v1"
	metricspb "go.opentelemetry.io/proto/otlp/metrics/v1"
	resourcepb "go.opentelemetry.io/proto/otlp/resource/v1"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/timestamppb"
	"k8s.io/klog/v2"
)

var gzipWriterPool = sync.Pool{
	New: func() interface{} {
		return gzip.NewWriter(io.Discard)
	},
}

// encodeOTLP builds a gzipped OTLP/HTTP request body.
//
// A store must end up with the same series as over remote write, because queries
// select by exact name and by 'job' and 'instance'. So names are sent as they are
// with no unit (stores derive suffixes from units), and 'job' and 'instance' are
// set on every data point (not every store derives them from service.*).
func encodeOTLP(mfs []*dto.MetricFamily, timestampMs int64, extraLabels map[string]string) ([]byte, error) {
	data, err := proto.Marshal(buildOTLPRequest(mfs, timestampMs, extraLabels))
	if err != nil {
		return nil, err
	}
	buf := &bytes.Buffer{}
	w := gzipWriterPool.Get().(*gzip.Writer)
	w.Reset(buf)
	defer gzipWriterPool.Put(w)
	if _, err = w.Write(data); err != nil {
		return nil, err
	}
	if err = w.Close(); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

Comment thread prom/otlp.go
Comment on lines +182 to +195
// logRejectedPoints reports data points a receiver refused while accepting the request.
func logRejectedPoints(body io.Reader) {
data, err := io.ReadAll(io.LimitReader(body, 64*1024))
if err != nil {
return
}
res := &collectorpb.ExportMetricsServiceResponse{}
if err = proto.Unmarshal(data, res); err != nil {
return
}
if ps := res.GetPartialSuccess(); ps.GetRejectedDataPoints() > 0 {
klog.Warningf("the receiver rejected %d data points: %s", ps.GetRejectedDataPoints(), ps.GetErrorMessage())
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Add a helper function readErrorBody to read a short summary of the response body. This will be used in remote_writer.go to log detailed rejection reasons from the collector.

// logRejectedPoints reports data points a receiver refused while accepting the request.
func logRejectedPoints(body io.Reader) {
	data, err := io.ReadAll(io.LimitReader(body, 64*1024))
	if err != nil {
		return
	}
	res := &collectorpb.ExportMetricsServiceResponse{}
	if err = proto.Unmarshal(data, res); err != nil {
		return
	}
	if ps := res.GetPartialSuccess(); ps.GetRejectedDataPoints() > 0 {
		klog.Warningf("the receiver rejected %d data points: %s", ps.GetRejectedDataPoints(), ps.GetErrorMessage())
	}
}

// readErrorBody reads a short summary of the response body for error reporting.
func readErrorBody(body io.Reader) string {
	data, err := io.ReadAll(io.LimitReader(body, 1024))
	if err != nil {
		return ""
	}
	return strings.TrimSpace(string(data))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant